package com.longlong.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

/**
 * 接口文档配置嘞
 */

@Configuration

public class SwaggerConfig {


    /**
     * 创建接口文档
     * @return
     */
    @Bean
    public Docket createApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.longlong"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContext());
    }

    /**
     * 设置文档信息
     * @return
     */
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("艾慕有声")
                .version("1.0.0")
                .contact(new Contact("龙龙",null,"1301966496@qq.com"))
                .description("艾慕有声接口文档")
                .build();
    }


    /**
     * 请求头信息
     * @return
     */
    private List<ApiKey> securitySchemes(){
        List<ApiKey> list = new ArrayList<>();
        ApiKey apiKey = new ApiKey("Authorization", "Authorization", "Header");

        list.add(apiKey);
        return list;
    }

    /**
     * 配饰security对swagger测试的权限
     * @return
     */
    private List<SecurityContext> securityContext(){
        List<SecurityContext> list = new ArrayList<>();
        list.add(getSecurityContext());
        return list;

    }


    /**
     * 等到授权路径
     * @return
     */
    private SecurityContext getSecurityContext(){
        return SecurityContext.builder()
                .securityReferences(getSecurityReferences())
                .forPaths(PathSelectors.regex("hello/.*"))
                .build();
    }

    /**
     * 给授权swagger，可以进行接口测试
     * @return
     */
    private List<SecurityReference> getSecurityReferences(){
        List<SecurityReference> list = new ArrayList<>();
        //授权范围全局
        AuthorizationScope scope = new AuthorizationScope("global","accessEverything");
        AuthorizationScope[] scppes = new AuthorizationScope[1];

        scppes[0] = scope;
        list.add(new SecurityReference("Authorization",scppes));
        return list;



    }


}


















